import axios from 'axios'
import 'element-ui/lib/theme-chalk/index.css';
import { Loading,Message } from 'element-ui'

let loadingInstance = null;
	
const service = axios.create({
    baseURL: '',
    timeout: 5000
})
service.interceptors.request.use( config => {
	let token = window.sessionStorage.getItem('api-token')
	config.headers['authorization'] = 'Bearer ' + token;
    return config;
}, error => {
    return Promise.reject(error);
})

service.interceptors.response.use(response => {
    if(response.status === 200){
        return response.data
    }else{
		Message.error(JSON.stringify(response))
		return response
    }
}, error => {
    return Promise.reject(error);
})


//返回一个Promise(发送post请求)
function POST(url, params) {
    return new Promise((resolve, reject) => {
        service.post(url, params)
            .then(response => {
                resolve(response);
            }, err => {
                reject(err);
            })
            .catch((error) => {
                reject(error)
            })
    })
}

//返回一个Promise(发送get请求)
function GET(url, param) {
    return new Promise((resolve, reject) => {
        service.get(url, {
            params: param
        }).then(response => {
                resolve(response)
        }, err => {
                reject(err)
        }).catch((error) => {
                reject(error)
        })
    })
}

function POSTFORMAT(url, params) {
    return new Promise((resolve, reject) => {
        service({
            url: url,
            method: 'post',
            data: params,
            headers: {
                "Content-Type": "multipart/form-data"
            }
        }).then(response => {
            resolve(response);
        }, err => {
            reject(err);
        }).catch((error) => {
                reject(error)
        })
    })
}

async function asyncPost(url, params) {
	params = params || {}
	try {
	    let res = await service.post(url,params);
		if (res.code !== 200) {
			Message.error(res.message)
			return [res.message, res]
		}
	    return [null, res]
	} catch (e) {
	    return [e, null]
	}
}

async function asyncGet(url, params) {
	params = params || {}
	try {
	    let res = await service.get(url,{ params: params});
		if (res.code !== 200) {
			Message.error(res.message)
			return [res.message, res]
		}
	    return [null, res]
	} catch (e) {
	    return [e, null]
	}
}

export  {service as AXIOS,POST,GET,POSTFORMAT,asyncPost,asyncGet}
